//
//  BankMap.m
//  SZBank
//
//  Created by LuoYao on 16/7/13.
//  Copyright © 2016年 LuoYao. All rights reserved.
//

#import "BankMap.h"
#import "BankMapTableViewCell.h"

@interface BankMap ()<ButtonAndTableViewDelegate,MKMapViewDelegate,UITableViewDelegate,UITableViewDataSource,CLLocationManagerDelegate>
{
    NSDictionary *_mapDataSource;/**< 下拉选择的城市名称 */
    NSArray *_bankArray;/**< 网点地址 */
    NSMutableArray *_nowCityBank;/**< 当前城市网点 */
    NSDictionary *_nearByDic;/**< 附近下拉数据 */
    CLLocationManager *_local;//定位管理器
    NSInteger index;/**< 大头针数字 */
}
@property (nonatomic) ButtonAndTableView *btnTable;/**< 下拉选择 */
@property (nonatomic) UITableView *tableView;/**< 显示当前页面银行信息 */
@property (nonatomic) ButtonAndTableView *nearByTabel;/**< 附近下拉 */

@end
@implementation BankMap

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backImageView.image = [LocalDataManager getImageWithSourceOfPath:@"背景"];
        
        [self locationManager];
        [self addSubview:self.mapView];
        
        
        //城市数据
       _mapDataSource = @{@"title":@"江苏省",@"list":@[@"南京市",@"无锡市",@"徐州市",@"常州市",@"苏州市",@"南通市",@"连云港市",@"淮安市",@"盐城市",@"扬州市",@"镇江市",@"泰州市",@"宿迁市"]};
        [self addSubview: self.btnTable];
        
        //附近下拉数据
        _nearByDic = @{@"title":@"附近",@"list":@[@"附近500米",@"附近1000米",@"附近2000米",@"附近5000米"]};
        [self addSubview:self.nearByTabel];
        
        //网络请求网点列表
        [NetWorkingDataManager getprotocol_web_siteWithParam:@{@"time":@"2010-01-01 12:00:12"} success:^(id sender) {
            _bankArray = sender[@"updateList"];
            
        } failure:^(id sender) {
            
        }];
        
        
        
        [self addSubview: self.tableView];
        
        
    }
    return self;
}




#pragma mark - btntable协议
- (void)btnTableView:(ButtonAndTableView *)btnTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath selectTitle:(NSString *)selectTitle{
    
    //地图更新
    [self showLatitudeFromCityName:selectTitle];
    
    _nowCityBank = [NSMutableArray array];
    
    BOOL isRange = NO;
    //遍历银行网点地址
    for (NSDictionary *dic in _bankArray) {
        NSString *address = dic[@"ADDRESS"];
        //判断是否包含当前选择城市
        if ([address rangeOfString:[selectTitle substringToIndex:2]].location != NSNotFound) {
            isRange = YES;
            [_nowCityBank addObject:dic];
        }
    }
    
    //如果存在在地图上进行标点
    if (isRange) {
        //index置为0
        index = 0;
        
        for (int i = 0; i < _nowCityBank.count; i ++) {
            //大头针标点
            index = i + 1;
            [self showPointOfLatitude:_nowCityBank[i]];
            
        }
        
    }
    
    [self.tableView reloadData];
    
}



//我的位置管理
- (void)locationManager{
    
    _local = [[CLLocationManager alloc] init];
    [_local requestWhenInUseAuthorization];//设置定位后台
    _local.desiredAccuracy = kCLLocationAccuracyBest;//定位精度
    _local.distanceFilter = 1000;//跟踪距离
    _local.delegate = self;
    [_local startUpdatingLocation];//开始定位
}


//地图标点
- (void)showPointOfLatitude:(NSDictionary *)dic{
    
    //字符转化
    CGFloat latitude = [dic[@"LATITUDE"] floatValue];
    CGFloat longtitude = [dic[@"LONGITUDE"] floatValue];
    
    //设置地图显示的中心点及缩放比例
    CLLocationCoordinate2D center = {latitude,longtitude};
    MKCoordinateSpan span;
    
    span.latitudeDelta = 1;
    span.longitudeDelta = 1;
    
    MKCoordinateRegion region = {center,span};
    
    [self.mapView setRegion:region animated:YES];
    
    
    if ([dic count] > 2) {
        
        MKPointAnnotation *anno = [[MKPointAnnotation alloc] init];
        anno.title = dic[@"NAME"];
        anno.subtitle = dic[@"ADDRESS"];
        anno.coordinate = center;
        
        //调用此方法在地图上加坐标点
        [self.mapView addAnnotation:anno];
    }
    
    
}


#pragma mark - 根据地名确定经纬度
- (void)showLatitudeFromCityName:(NSString *)cityName {
    
       __block  NSDictionary *dic = [NSDictionary dictionary];
    
    CLGeocoder *myGeocoder = [[CLGeocoder alloc] init];
    [myGeocoder geocodeAddressString:cityName completionHandler:^(NSArray *placemarks, NSError *error) {
        if ([placemarks count] > 0 && error == nil)
        {
            CLPlacemark *firstPlacemark = [placemarks objectAtIndex:0];
            
            
            dic = @{@"LONGITUDE":@(firstPlacemark.location.coordinate.longitude),
                    @"LATITUDE":@(firstPlacemark.location.coordinate.latitude)
                    };
            
            [self showPointOfLatitude:dic];
        }
        else if ([placemarks count] == 0 && error == nil)
        {
            NSLog(@"Found no placemarks.");
        }
        else if (error != nil)
        {
            NSLog(@"An error occurred = %@", error);
        }
    }];
}


#pragma mark - localManagerDelegate
//我的位置获取之后执行方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
   CLLocation *location = locations.lastObject;
    NSDictionary *dic = @{@"LONGITUDE":@(location.coordinate.longitude),
                                @"LATITUDE":@(location.coordinate.latitude)
                                };
    //更新位置
    [self showPointOfLatitude:dic];
}

//定位失败
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    [LocalDataManager addAlertControllerWithControllerTitle:@"提示" controllerMessage:@"定位失败，检查设备后重试！" actionSureTitle:@"确定" actionCancelTile:nil actionSureBlock:nil actionCancelBlock:nil style:0];
}


#pragma mark - mapView协议
//返回自定大头针方法
- (nullable MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
    
    //重用队列中去取
    MKAnnotationView *annoView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"annoId"];
    if (!annoView) {
        annoView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"annoId"];
        
        //数字编号
        UILabel *numberLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 40, 40)];
        numberLabel.textColor = [UIColor whiteColor];
        
        numberLabel.text = [NSString stringWithFormat:@"%ld",index];
        [annoView addSubview:numberLabel];
    }
    annoView.image = [LocalDataManager getImageWithSourceOfPath:@"地图_列表图标"];
    
    //点击大头针后弹窗
    annoView.canShowCallout = YES;
    
    
    return annoView;
}




#pragma mark - UItableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_nowCityBank == nil) {
        return 0;
    }else{
        return _nowCityBank.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BankMapTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tablecell" forIndexPath:indexPath];
    
    cell.label.text = [NSString stringWithFormat:@"%ld",indexPath.row + 1];
    cell.bankName.text = _nowCityBank[indexPath.row][@"NAME"];
    cell.bankAddress.text = _nowCityBank[indexPath.row][@"ADDRESS"];
    [cell.bankAddress sizeToFit];
    
    cell.bankPhone.text = _nowCityBank[indexPath.row][@"PHONE"];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 170;
}




#pragma mark - 点击事件
- (void)action_btn:(UIButton *)sender{
    
}

#pragma mark - getter
- (MKMapView *)mapView{
    if (!_mapView) {
        _mapView = [[MKMapView alloc] initWithFrame:CGRectMake(_cKwidth * 0.03, _cKheight * 0.1, _cKwidth * 0.6, _cKheight * 0.8)];
        _mapView.delegate = self;
        _mapView.showsUserLocation = YES;//显示当前位置
    }
    return _mapView;
}


- (ButtonAndTableView *)btnTable{
    if (!_btnTable) {
        _btnTable = [[ButtonAndTableView alloc] initWithFrame:CGRectMake(_cKwidth * 0.15, _cKheight * 0.02, _cKwidth * 0.15, _cKheight * 0.04) dataSource:_mapDataSource backImageName:@"地图_城市下拉框" selectImageName:@"地图_城市下拉框"];
        _btnTable.delegate = self;
    }
    return _btnTable;
}

- (ButtonAndTableView *)nearByTabel{
    if (!_nearByTabel) {
        _nearByTabel = [[ButtonAndTableView alloc] initWithFrame:CGRectMake(_cKwidth * 0.8, _cKheight * 0.02, _cKwidth * 0.15, _cKheight * 0.04) dataSource:_nearByDic backImageName:@"地图_附近查询底" selectImageName:@"地图_附近查询底"];
        _nearByTabel.delegate = self;
        
    }
    return _nearByTabel;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(_cKwidth * 0.7, _cKheight * 0.1, _cKwidth * 0.25, _cKheight * 0.8) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        [_tableView registerClass:[BankMapTableViewCell class] forCellReuseIdentifier:@"tablecell"];
    }
    return _tableView;
}
@end
